package com.whw.fy.service.impl;

import com.alibaba.fastjson.JSON;
import com.whw.fy.entity.*;
import com.whw.fy.mapper.*;
import com.whw.fy.utils.AgeUtil;
import com.whw.fy.utils.GetEveryDate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.whw.fy.entity.AttendanceStu;
import com.whw.fy.service.StudentService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private ParentMapper parentMapper;
    @Resource
    private ClazzMapper clazzMapper;
    @Resource
    private AttendanceStuMapper attendanceStuMapper;
    @Resource
    private TrainingInstitutionRecordsMapper trainingInstitutionRecordsMapper;
    @Resource
    private EmergencyMapper emergencyMapper;
    @Resource
    private PurchaseCourseRecordsMapper purchaseCourseRecordsMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private StaffMapper staffMapper;

    @Override
    public Message deleteByPrimaryKey(Integer studentId) {
        return studentMapper.deleteByPrimaryKey(studentId) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message insert(Student record) {
        return studentMapper.insert(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message insertSelective(Student record) {
        if (record.getStudentHeadImages() == null) {
            record.setStudentHeadImages("https://www.whwmiki.cn/fy//resource/f430a8fb-fd38-42da-9333-2f9fc72f59e2.png");
        }
        if (studentMapper.insertSelective(record) > 0) {
            int stuId = record.getStudentId();
            if (record.getStudentTreatTrainingInstitutionRecords() != null) {
                String ids[] = record.getStudentTreatTrainingInstitutionRecords().split(";");

                for (String id : ids) {
                    trainingInstitutionRecordsMapper.updateStudentIdByTrainingInstitutionRecordId(stuId, Integer.parseInt(id));
                }
            }
            return Message.success("添加成功！");
        } else {
            return Message.fail("添加学生失败！");
        }
    }



    @Override
    public Message updateByPrimaryKeySelective(Student record) throws ParseException {
        if (record.getStudentBirthtoString() != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            record.setStudentBirth(simpleDateFormat.parse(record.getStudentBirthtoString()));
        }
        if (record.getStudentJoinCentertoString() != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            record.setStudentJoinCenter(simpleDateFormat.parse(record.getStudentJoinCentertoString()));
        }

        return studentMapper.updateByPrimaryKeySelective(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message updateByPrimaryKey(Student record) {
        return studentMapper.updateByPrimaryKey(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message selectAll() {
        List<Student> studentList = studentMapper.selectAll();
        return Message.success(null).add(initStudentList(studentList));
    }

    @Override
    public Message selectStudentNameAndAdd() {
        List<Student> studentList = studentMapper.selectAll();
        List<Map> mapList = new LinkedList<>();
        for (Student student : studentList) {
            HashMap hashMap = new HashMap();
            hashMap.put("studentId", student.getStudentId());
            hashMap.put("String", student.getStudentName() + "<" + student.getStudentAddress() + ">");
            mapList.add(hashMap);
        }
        return Message.success(null).add(mapList);
    }

    @Override
    public Message parentinsert(Student student) throws ParseException {
        if (studentMapper.insertSelective(student) > 0) {
            HashMap hashMap = new HashMap();
            hashMap.put("studentId", student.getStudentId());
            hashMap.put("String", student.getStudentName() + "<" + student.getStudentAddress() + ">");
            return Message.success(null).add(hashMap);
        } else return Message.fail("添加孩子失败！");


    }


    @Override
    public Message selectStudentNameAndAddByParentId(int parentId) {
        Parent parent = parentMapper.selectByPrimaryKey(parentId);
        String ids[] = parent.getChildId().split(";");
        List<Map> mapList = new LinkedList<>();
        for (String studentId : ids) {
            Student student = studentMapper.selectByPrimaryKey(Integer.parseInt(studentId));
            if (student != null) {
                HashMap map = new HashMap();
                map.put("studentId", studentId);
                map.put("String", student.getStudentName() + "<" + student.getStudentAddress() + ">");
                mapList.add(map);
            }

        }
        return Message.success(null).add(mapList);
    }

    @Override
    public Message selectStudentNameAndAddByClassId(int ClassId) {
        Clazz clazz = clazzMapper.selectByPrimaryKey(ClassId);
        String ids[] = clazz.getStudentId().split(";");
        List<Map> mapList = new LinkedList<>();
        for (String studentId : ids) {
            Student student = studentMapper.selectByPrimaryKey(Integer.parseInt(studentId));
            if (student != null) {
                HashMap map = new HashMap();
                map.put("studentId", studentId);
                map.put("String", student.getStudentName() + "<" + student.getStudentAddress() + ">");
                mapList.add(map);
            }

        }
        return Message.success(null).add(mapList);
    }

    @Override
    public int batchInsert(List<Student> list) {
        return studentMapper.batchInsert(list);
    }

    @Override
    public Message selectPurchaseAndEmergencyByStudentId(int studentId) {
        HashMap hashMap = new HashMap();
        hashMap.put("purchase", purchaseCourseRecordsMapper.selectByStudentId(studentId));
        hashMap.put("emergency", emergencyMapper.selectByEmergencyStudentId(studentId));
        return Message.success(null).add(hashMap);
    }

    @Override
    public Message selectCommentByStudentId(int studentId) {
        List<AttendanceStu> AttendanceStuList = attendanceStuMapper.selectByStudentId(studentId);
        List<Map> mapList = new LinkedList<>();
        for (AttendanceStu attendanceStu : AttendanceStuList) {
            HashMap hashMap = new HashMap();
            hashMap.put("attendanceStu", attendanceStu);
            hashMap.put("comment", commentMapper.selectAllByCommClassIdAndCommByReviewersAndCommClassSkcdAndCommType(attendanceStu.getClassId(), attendanceStu.getStudentId(), attendanceStu.getCompletionTimes(), "3;1"));
            hashMap.put("emergency", emergencyMapper.selectAllByEmergencyClazzIdAndEmergencyStudentIdAndEmergencyClazzSkcd(attendanceStu.getClassId(), attendanceStu.getStudentId(), attendanceStu.getCompletionTimes()));
            mapList.add(hashMap);
        }
        return Message.success(null).add(mapList);
    }

    @Override
    public Message newAdd(Student record, List<TrainingInstitutionRecords> list) {
        record.setStudentJoinCenter(new Date());
        if (record.getStudentHeadImages() == null) {
            record.setStudentHeadImages("https://www.whwmiki.cn/fy//resource/f430a8fb-fd38-42da-9333-2f9fc72f59e2.png");
        }
        System.out.println(list);
        System.out.println(record);
        String trainId = "";
        if (studentMapper.insertSelective(record) > 0) {
            int stuId = record.getStudentId();
            for (TrainingInstitutionRecords t : list) {
                t.setStudentId(stuId);
                if (trainingInstitutionRecordsMapper.insertSelective(t) > 0) {
                    trainId = trainId + t.getTrainingInstitutionRecordId() + ";";
                }
            }
            record.setStudentTreatTrainingInstitutionRecords(trainId);
            studentMapper.updateByPrimaryKey(record);
            return Message.success("添加成功！");
        } else {
            return Message.fail("添加学生失败！");
        }
    }

    @Override
    public Message newUpdate(Student student, String list1) {
        if (list1!=null){
            List<TrainingInstitutionRecords> list = JSON.parseArray(list1,TrainingInstitutionRecords.class);
            String trainId = "";
            for (TrainingInstitutionRecords t : list) {
                if (t.getTrainingInstitutionRecordId() == null) {
                    if (trainingInstitutionRecordsMapper.insertSelective(t) > 0)
                        trainId = trainId + t.getTrainingInstitutionRecordId() + ";";
                } else {
                    if (trainingInstitutionRecordsMapper.updateByPrimaryKeySelective(t) > 0)
                        trainId = trainId + t.getTrainingInstitutionRecordId() + ";";
                }
            }
            student.setStudentTreatTrainingInstitutionRecords(trainId);
        }
        return studentMapper.updateByPrimaryKeySelective(student) > 0 ? Message.success("修改成功") : Message.fail("修改失败");
    }

    @Override
    public Message insertStudentTreat(Student student) {
        student.setStudentTreatPostTime(new Date());
        return studentMapper.updateByPrimaryKeySelective(student) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message selectallByMedicalDirectorIdJurisdictionZero(int staffId) {
        List<Student> studentList = studentMapper.selectByStudentTreatMedicalDirectorId(staffId);
        return Message.success(null).add(initStudentList(studentList));
    }

    @Override
    public Message selectallByprincipalTeacherJurisdictionSeven(int staffId) {
        List<Student> studentList = studentMapper.selectAllByStudentTreatPrincipalTeacherId(staffId);
        return Message.success(null).add(initStudentList(studentList));
    }

    @Override
    public Message selectallByTeachingDirectorJurisdictionSix(int staffId) {
        List<Student> studentList = studentMapper.selectByStudentTreatTeachingDirectorId(staffId);
        return Message.success(null).add(initStudentList(studentList));
    }

    @Override
    public Message selectallByTeacherIdJurisdictionEight(int staffId) {
        //拿到全部学生id
        List<Clazz> clazzList = clazzMapper.selectByClassTeacherId(staffId);
        List<Integer> studentIdList = new LinkedList<>();
        for (Clazz clazz : clazzList) {
            if (clazz.getStudentId() != null) {
                String ids[] = clazz.getStudentId().split(";");
                if (ids.length > 0) {
                    for (String studentId : ids) {
                        studentIdList.add(Integer.parseInt(studentId));
                    }
                }
            }
        }
        studentIdList = duplicate(studentIdList);

        List<Student> studentList = new LinkedList<>();
        //拿到学生信息
        for (Integer id : studentIdList) {
            studentList.add(studentMapper.selectByPrimaryKey(id));
        }
        return Message.success(null).add(initStudentList(studentList));
    }

    /**
     * 对list的数据的的obj 进行去重
     *
     * @param list
     * @return
     */
    private List duplicate(List list) {
        List listTemp = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (!listTemp.contains(list.get(i))) {
                listTemp.add(list.get(i));
            }
        }
        Collections.sort(listTemp);
        return listTemp;
    }

    @Override
    public Message selectByPrimaryKey(Integer studentId) {
        Student student = studentMapper.selectByPrimaryKey(studentId);
        Date nowdate = new Date();
        //根据学生出生日期动态设置学生年龄
        if (student.getStudentBirth() != null) {
            student.setStudentAge(AgeUtil.getAgeByBirth(student.getStudentBirth()));
        } else {
            student.setStudentAge(-1);
        }
        //根据学生加入中心日期动态设置学生加入时长
        student.setStudentJoinTime(GetEveryDate.GetTimeBetween(student.getStudentJoinCenter(), nowdate));

        //临床信息查询
        if (student.getStudentTreatMedicalDirectorId() != null)
            student.setStudentTreatMedicalDirectorName(
                    staffMapper.selectByPrimaryKey(student.getStudentTreatMedicalDirectorId()).getStaffName()
                            + "<" + student.getStudentTreatMedicalDirectorId() + ">");
        if (student.getStudentTreatPrincipalTeacherId() != null)
            student.setStudentTreatPrincipalTeacherName(
                    staffMapper.selectByPrimaryKey(student.getStudentTreatPrincipalTeacherId()).getStaffName()
                            + "<" + student.getStudentTreatPrincipalTeacherId() + ">");
        if (student.getStudentTreatTeachingDirectorId() != null)
            student.setStudentTreatTeachingDirectorName(
                    staffMapper.selectByPrimaryKey(student.getStudentTreatTeachingDirectorId()).getStaffName()
                            + "<" + student.getStudentTreatTeachingDirectorId() + ">");
        //父母身份证号查询
        if(student.getStudentFatherId() != null)
            student.setStudentFatherIdCard(
                    parentMapper.selectByPrimaryKey(student.getStudentFatherId()).getParentIdcard());
        if(student.getStudentMotherId() != null)
            student.setStudentMotherIdCard(
                    parentMapper.selectByPrimaryKey(student.getStudentMotherId()).getParentIdcard());

        List<TrainingInstitutionRecords> recordsList = new LinkedList<>();
        if (student.getStudentTreatTrainingInstitutionRecords() != null) {
            String ids[] = student.getStudentTreatTrainingInstitutionRecords().split(";");

            for (String id : ids) {
                if (id.equals("")) {
                } else {
                    TrainingInstitutionRecords record = trainingInstitutionRecordsMapper.selectByPrimaryKey(Integer.parseInt(id));
                    if (record != null)
                        recordsList.add(record);
                }


            }
        }
        HashMap hashMap = new HashMap();
        hashMap.put("student", student);
        hashMap.put("TrainingInstitutionRecords", recordsList);
        return Message.success(null).add(hashMap);
    }

    //对从数据库查询到的studentList进行封装
    private List<Student> initStudentList(List<Student> studentList) {
        Date nowdate = new Date();
        for (Student student : studentList) {
            //根据学生出生日期动态设置学生年龄
            if (student.getStudentBirth() != null) {
                student.setStudentAge(AgeUtil.getAgeByBirth(student.getStudentBirth()));
            } else {
                student.setStudentAge(-1);
            }
            //根据学生加入中心日期动态设置学生加入时长
            student.setStudentJoinTime(GetEveryDate.GetTimeBetween(student.getStudentJoinCenter(), nowdate));

            //临床信息查询
            if (student.getStudentTreatMedicalDirectorId() != null)
                student.setStudentTreatMedicalDirectorName(
                        staffMapper.selectByPrimaryKey(student.getStudentTreatMedicalDirectorId()).getStaffName()
                                + "<" + student.getStudentTreatMedicalDirectorId() + ">");
            if (student.getStudentTreatPrincipalTeacherId() != null)
                student.setStudentTreatPrincipalTeacherName(
                        staffMapper.selectByPrimaryKey(student.getStudentTreatPrincipalTeacherId()).getStaffName()
                                + "<" + student.getStudentTreatPrincipalTeacherId() + ">");
            if (student.getStudentTreatTeachingDirectorId() != null)
                student.setStudentTreatTeachingDirectorName(
                        staffMapper.selectByPrimaryKey(student.getStudentTreatTeachingDirectorId()).getStaffName()
                                + "<" + student.getStudentTreatTeachingDirectorId() + ">");
        }
        return studentList;
    }

    @Override
    public int updateBatch(List<Student> list) {
        return studentMapper.updateBatch(list);
    }

    @Override
    public int updateBatchSelective(List<Student> list) {
        return studentMapper.updateBatchSelective(list);
    }


}







